package com.sky.service.rider.Impl;

import cn.hutool.core.date.DateException;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.CodeExpiredException;
import com.sky.exception.CourierNotExistException;
import com.sky.pojo.Courier;
import com.sky.result.Result;
import com.sky.service.rider.CourierService;
import com.sky.service.rider.LoginService;
import com.sky.utils.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CourierService courierService;
    @Override
    public String validateCodeToPhone(String telephone) throws Exception {
        //1.短信发送
        String code = "";
        //生成随机6为数字得验证🐎
        Random random = new Random();
        for(int i=0;i<4;i++){
            code+=random.nextInt(10);
        }
        //短息发送
//        SendSms.sendMessage(telephone,code);
        //2.保存到redis
        String key = "code:"+telephone;
        redisTemplate.opsForValue().set(key,code,600, TimeUnit.SECONDS);
        return code;
    }

    @Override
    public Courier login(UserLoginDTO dto) {
        if (null==dto || null == dto.getCode()){
            throw new DateException(MessageConstant.DATA_ERROR);
        }
        String key= "code:"+dto.getTelephone();
        Object code = redisTemplate.opsForValue().get(key);
        if (null==code){
            throw new CodeExpiredException("验证码已经过期了");
        }
        if (!dto.getCode().equals(code.toString())){
            throw new CodeExpiredException("验证码错误");
        }
      Courier courier =  courierService.selectByPhone(dto.getTelephone());
        if (null==courier){
            throw new CourierNotExistException("骑手不存在,请先注册为骑手");
        }
        return courier;
    }
}
